package fr.upmc.aladyn.transactionablesMetaObject;

import java.lang.reflect.Method;

import fr.upmc.aladyn.transactionables.Transactionable;
import javassist.tools.reflect.Metaobject;


/**
 * Class that defines the meta object. This meta object saves an object and restores it
 * if a problem occurs.
 * @author Ritchie Nithoo
 * @author Jules Fabry
 * @version 1.0

 */
public class SaveMetaObj extends Metaobject {



	private static final long serialVersionUID = 1L;

	public SaveMetaObj(Object self, Object[] args) {
		super(self, args);
	}

	public Object trapMethodcall(int indentifier, Object[] args) {
		Method m = getClassMetaobject().getMethod(indentifier);
		Object o = null;
		if (m.getName().contains("set")) {
			fr.upmc.aladyn.transactionables.BackUpManager.save(getObject());
			try {
				return super.trapMethodcall(indentifier, args);
			} catch (Throwable e) {
				System.out.println("*****catch du m.getName()*****");
			}
		}
		if (m.isAnnotationPresent(Transactionable.class)) {
			try {
				fr.upmc.aladyn.transactionables.BackUpManager.begin();
				o = super.trapMethodcall(indentifier, args);
			}catch (Throwable e) {
				System.out.println("*****catch du m.isAnnotationPresent()*****");
				fr.upmc.aladyn.transactionables.BackUpManager.restore();
			}
//			fr.upmc.aladyn.transactionables.BackUpManager.restore();
			fr.upmc.aladyn.transactionables.BackUpManager.end();
		} else {
			try {
				o = super.trapMethodcall(indentifier, args);
			} catch (Throwable e) {
				System.out.println("*****catch du trapmethodCall du else*****");
			}
		}

		return o;
	}

	public void trapFieldWrite(String name, Object Value) {
		// getClassMetaobject().getMethod(indentifier)
		super.trapFieldWrite(name, Value);
	}

	public Object trapFieldRead(String name) {
		return super.trapFieldRead(name);
	}

}
